package hy.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
@ImportResource(locations="classpath:u.xml")
@Configuration
@MapperScan(basePackages = "hy.dao.order", sqlSessionFactoryRef = "sqlSessionFactoryBean_1")
@MapperScan(basePackages = "hy.dao.store", sqlSessionFactoryRef = "sqlSessionFactoryBean_2")
public class DataSourceConfig {
    @Bean("xaDs1")
    @ConfigurationProperties("spring.datasource.order")
    public DruidXADataSource getDs1(){
        return new DruidXADataSource();
    }
    @Bean("xaDs2")
    @ConfigurationProperties("spring.datasource.store")
    public DruidXADataSource getDs2(){
        return new DruidXADataSource();
    }

    @Bean("ds1")
    public DataSource firstDataSource(@Qualifier("xaDs1") DruidXADataSource xaDs1){
        //创建atomikos数据源
        AtomikosDataSourceBean bean = new AtomikosDataSourceBean();
        bean.setXaDataSource(xaDs1);
        return bean;
    }
    @Bean("ds2")
    public DataSource secondDataSource(@Qualifier("xaDs2") DruidXADataSource xaDs2){
        //创建atomikos数据源
        AtomikosDataSourceBean bean = new AtomikosDataSourceBean();
        bean.setXaDataSource(xaDs2);
        return bean;
    }
    @Bean("sqlSessionFactoryBean_1")
    public SqlSessionFactoryBean s1(@Qualifier("ds1")DataSource ds) throws IOException {
        //创建SqlSessionFactoryBean对象
        SqlSessionFactoryBean s = new SqlSessionFactoryBean();
        s.setDataSource(ds);
        //设置mapper映射文件路径
        ResourcePatternResolver rs = new PathMatchingResourcePatternResolver();
        s.setMapperLocations(rs.getResources("classpath:/mapper/order/*.xml"));
        return s;
    }
    @Bean("sqlSessionFactoryBean_2")
    public SqlSessionFactoryBean s2(@Qualifier("ds2")DataSource ds) throws IOException {
        //创建SqlSessionFactoryBean对象
        SqlSessionFactoryBean s = new SqlSessionFactoryBean();
        s.setDataSource(ds);
        //设置mapper映射文件路径
        ResourcePatternResolver rs = new PathMatchingResourcePatternResolver();
        s.setMapperLocations(rs.getResources("classpath:/mapper/store/*.xml"));
        return s;
    }
}